#include "room_manager.h"

RoomManager::RoomManager()
{
    rooms["lobby"] = Room("lobby");
}

bool RoomManager::join(int fd, const std::string& room_name, const std::string& pwd, std::string& err)
{
    auto it = rooms.find(room_name);

    if(it == rooms.end())
        rooms[room_name] = Room(room_name, pwd);
    else
        if(it->second.password != pwd)
        {
            err = "[Server] Room exists but password mismatch.\n";
            return false;
        }

    for(auto& [room_name ,room] : rooms) room.remove(fd);
    rooms[room_name].add(fd);
    return true;
}

void RoomManager::leave(int fd)
{
    for(auto& [room_name, room] : rooms) room.remove(fd);
}

std::string RoomManager::get_user_room(int fd) const
{
    for(const auto& [name, room] : rooms)
    {
        if(room.has(fd)) return name;
    }
    return "lobby";
}

std::vector<int> RoomManager::get_members(const std::string& room_name) const
{
    std::vector<int> v;
    auto it = rooms.find(room_name);
    if(it != rooms.end())
    {
        for(int fd : it->second.members)
            v.push_back(fd);
    }
    return v;
}

std::unordered_map<std::string, std::set<int>> RoomManager::get_all_rooms() const {
    std::unordered_map<std::string, std::set<int>> res;
    for (const auto& [name, room] : rooms) {
        res[name] = room.members;
    }
    return res;
}

